package com.elegantmall.util;

import org.apache.commons.codec.binary.Base64;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Map;
import javax.imageio.ImageIO;
import java.text.ParseException;
import java.util.Date;

public class ChartUtil {
    
    /**
     * 生成销售趋势折线图
     *
     * @param salesTrend 销售趋势数据，键为日期字符串（格式：yyyy-MM-dd），值为销售额
     * @param title 图表标题
     * @return 图表的Base64编码字符串
     */
    public static String generateSalesTrendChart(Map<String, Double> salesTrend, String title) {
        try {
            // 创建时间序列数据集
            TimeSeries series = new TimeSeries("销售额");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            
            // 将销售趋势数据添加到时间序列中
            for (Map.Entry<String, Double> entry : salesTrend.entrySet()) {
                try {
                    Date date = dateFormat.parse(entry.getKey());
                    series.add(new Day(date), entry.getValue());
                } catch (ParseException e) {
                    // 跳过无法解析的日期
                    continue;
                }
            }
            
            // 创建数据集
            TimeSeriesCollection dataset = new TimeSeriesCollection();
            dataset.addSeries(series);
            
            // 创建JFreeChart对象
            JFreeChart chart = createTimeSeriesChart(dataset, title);
            
            // 将图表转换为Base64编码
            return chartToBase64(chart, 800, 400);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 创建时间序列图表
     */
    private static JFreeChart createTimeSeriesChart(XYDataset dataset, String title) {
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
                title,      // 图表标题
                "日期",     // x轴标签
                "销售额",   // y轴标签
                dataset,    // 数据集
                true,       // 是否显示图例
                true,       // 是否生成工具提示
                false       // 是否生成URL
        );
        
        // 设置图表样式
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(new Color(255, 255, 255));
        plot.setDomainGridlinePaint(new Color(220, 220, 220));
        plot.setRangeGridlinePaint(new Color(220, 220, 220));
        
        // 设置线条和形状渲染器
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesPaint(0, new Color(0, 121, 255));  // 设置线条颜色
        renderer.setSeriesStroke(0, new BasicStroke(2.0f));  // 设置线条粗细
        renderer.setSeriesShapesVisible(0, true);           // 在数据点显示形状
        plot.setRenderer(renderer);
        
        // 设置日期轴格式
        DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
        dateAxis.setDateFormatOverride(new SimpleDateFormat("MM-dd"));
        
        return chart;
    }
    
    /**
     * 将JFreeChart对象转换为Base64编码
     */
    private static String chartToBase64(JFreeChart chart, int width, int height) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(chart.createBufferedImage(width, height), "png", outputStream);
            return Base64.encodeBase64String(outputStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
} 